package com.example.gamestore.control;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.gamestore.Bean.User;
import com.example.gamestore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.sql.Wrapper;

@Controller
public class UserControl {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public String login(Model model, User user, HttpSession Session) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername())
                .eq("password", user.getPassword());
        User user1 = userService.getOne(wrapper);
        if (user1 != null) {
            Session.setAttribute("user",user1);
            return "redirect:/main";
        } else {
            model.addAttribute("error", "密码错误");
            return "index";
        }
    }

    @GetMapping("/main")
    public String loginsuccess() {
        return "index1";
    }

    @GetMapping("/registersuccess")
    public String registersuccess() {
        return "index";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        String username = user.getUsername();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username).last("limit 1");
        User user1 = userService.getOne(wrapper);
        if (user1 != null) {
            model.addAttribute("error", "用户名已经存在");
            return "register";
        }
        model.addAttribute("error","注册成功");
        return "redirect:/registersuccess";
    }
    @GetMapping("/logout")
    public String loginout(HttpSession session){
        session.removeAttribute("user");
        return "index";
    }
    @GetMapping("rlogin")
    public String rlogin(){
        return "index";
    }
}
